

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="MiaoHao-oops">
  <meta name="keywords" content="">
  
    <meta name="description" content="这篇文章于 1992 年首次提出了 BPF，即 “BSD Packet Filter”，并介绍了它的主要设计思路。">
<meta property="og:type" content="article">
<meta property="og:title" content="文献阅读: The BSD Packet Filter: A New Architecture for User-level Packet Capture">
<meta property="og:url" content="http://miaohao-oops.github.io/2024/03/05/%E6%96%87%E7%8C%AE%E9%98%85%E8%AF%BB-The-BSD-Packet-Filter-A-New-Architecture-for-User-level-Packet-Capture/index.html">
<meta property="og:site_name" content="Miao&#39;s Blog">
<meta property="og:description" content="这篇文章于 1992 年首次提出了 BPF，即 “BSD Packet Filter”，并介绍了它的主要设计思路。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://miaohao-oops.github.io/img/bpf-overview.png">
<meta property="og:image" content="http://miaohao-oops.github.io/img/Filter-Function-Representations.png">
<meta property="og:image" content="http://miaohao-oops.github.io/img/BPF-CSPF-Fileter-Performance.png">
<meta property="article:published_time" content="2024-03-05T05:31:35.000Z">
<meta property="article:modified_time" content="2024-03-11T07:08:18.620Z">
<meta property="article:author" content="MiaoHao-oops">
<meta property="article:tag" content="paper">
<meta property="article:tag" content="ebpf">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://miaohao-oops.github.io/img/bpf-overview.png">
  
  
  <title>文献阅读: The BSD Packet Filter: A New Architecture for User-level Packet Capture - Miao&#39;s Blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"miaohao-oops.github.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"appId":"y7tlaLEOoW5C1xBYm8VBo64Q-gzGzoHsz","appKey":"F7gylUefEEtQk24FEbvgfnBi","server_url":"https://y7tlaleo.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":true}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"><link rel="alternate" href="/atom.xml" title="Miao's Blog" type="application/atom+xml">
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>MiaoHao-oops</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="文献阅读: The BSD Packet Filter: A New Architecture for User-level Packet Capture">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2024-03-05 13:31" pubdate>
        2024年3月5日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.3k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      19 分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-page-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-page-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">文献阅读: The BSD Packet Filter: A New Architecture for User-level Packet Capture</h1>
            
            <div class="markdown-body">
              <h1
id="the-bsd-packet-filter-a-new-architecture-for-user-level-packet-capture">The
BSD Packet Filter: A New Architecture for User-level Packet Capture</h1>
<blockquote>
<p>论文作者：Steven Ray McCanne, Van L Jacobson</p>
<p>发表会议：USENIX'93</p>
<p>发表时间：January 1993</p>
</blockquote>
<h2 id="导览">0 导览</h2>
<p>1992 年的这篇文章首次提出了 BPF，即 “BSD Packet Filter”。最初 Unix
中的数据包过滤器是基于 stack 设计的，在 RISC CPU 中运行效率不高。BPF
基于 register 设计，比原来的设计快了 10 倍，整体性能比相同环境下的 NIT
快 100 倍。</p>
<p>本文主要介绍了 BPF 的设计思路，包括 BPF
的整体架构、理论模型（CFG）、伪语言翻译器、BPF 指令集，并给出了一些 BPF
过滤器的例子，最终通过测试验证了 BPF
的高效性。在文章主要内容的最后，给出了一些 BPF 已有的应用，从侧面说明了
BPF 设计的合理性，是真正能够运用到生产环境中的工具。</p>
<h2 id="introduction">1 Introduction</h2>
<p>BPF 的架构设计特点：</p>
<ul>
<li>register-based：在 RISC CPU 中能够得到更有效的实现，stack-based
面临存储墙问题</li>
<li>non-shared buffer model：得益于更大的地址空间</li>
</ul>
<h2 id="the-network-tap">2 The Network Tap</h2>
<p>BPF 的 2 个主要部件：</p>
<ol type="1">
<li>the network tap：从网络驱动收集包并复制给侦听程序</li>
<li>the packet filter：决定是否接受包，以及复制多少</li>
</ol>
<p><img src="/img/bpf-overview.png" srcset="/img/loading.gif" lazyload /></p>
<p>当网络数据包到达时：</p>
<ol type="1">
<li>link-level driver <strong>调用 BPF</strong></li>
<li>数据包经过 <strong>user-defined filter</strong></li>
<li>filter 决定哪些包可以被<strong>复制到 buffer</strong></li>
</ol>
<h3 id="packet-filtering">2.1 Packet Filtering</h3>
<p>BPF 相比于 NIT 性能提升的区别是 <strong>BPF 在 filter
之后才进行数据包的拷贝</strong>，而 NIT 是先进行拷贝再进行过滤，因此 NIT
浪费了许多 CPU 周期。</p>
<h3 id="tap-performance-measurements">2.2 Tap Performance
Measurements</h3>
<p>针对 BPF 和 NIT 的 packet-to-buffer 时间进行两组测试：</p>
<ul>
<li><strong>accept all</strong> <img
src="/img/NIT-vs-BPF-accept-all.png" srcset="/img/loading.gif" lazyload /> BPF 相比 NIT
有更缓慢的增长，y-截距是每个数据包处理的固定开销，BPF：6us，NIT：89us</li>
<li><strong>reject all</strong> <img
src="/img/NIT-vs-BPF-reject-all.png" srcset="/img/loading.gif" lazyload /> BPF 无增长，NIT
持续增长，最终甚至差了 2 个数量级。</li>
</ul>
<p>上面的测试结果体现了将 filter 和 tap 2
个单独的模块集成到一个单元中带来的巨大性能优势。</p>
<h2 id="the-filter-model">3 The Filter Model</h2>
<blockquote>
<p>Assuming one uses reasonable care inthe design ofthe buffering model,
it will be the dominant cost of packets you accept while <strong>the
packet filter computation will be the dominant cost of packets you
reject</strong>.</p>
</blockquote>
<p>大部分应用拒绝的包数远远大于接受的包数，因此 filter
的性能至关重要。filter 本质上是一个布尔函数，因此有 2 种表示方法：</p>
<ul>
<li>boolean expression tree/CSPF 描述表达式本身，契合于 stack-based
machine（对于一个表达式，我们可以利用栈来递归地进行求值）</li>
<li>CFG（控制流图） 描述表达式的执行流，更契合于 register-based
machine</li>
</ul>
<p><img src="/img/Filter-Function-Representations.png" srcset="/img/loading.gif" lazyload /></p>
<h3 id="the-cspftree-model">3.1 The CSPF(Tree) Model</h3>
<p>表达式求值实现上的弊端：</p>
<ul>
<li>需要模拟栈：额外的 add/sub
指令来控制栈指针寄存器，以维护一个栈，且频繁的栈访问成为性能瓶颈</li>
<li>通常包含冗余计算：如 <code>a | b</code>，我们无需将 <code>a</code>
和 <code>b</code>
的值都计算出来。这对于网络包过滤是很关键的，因为某些子表达式需要经过多层网络栈才能求值</li>
</ul>
<p>另一方面，CSPF 处理的数据有长度限制。</p>
<p>尽管 CSPF 有诸多限制，但是它提出了很新颖的思路：</p>
<ul>
<li>在内核中加入一个<strong>伪语言翻译器</strong>，以实现过滤器</li>
<li>将过滤的包视为字节数组，从而独立于网络协议</li>
</ul>
<h3 id="the-bpf-model">3.2 The BPF Model</h3>
<p>基于 CFG 的 BPF
的伪机器（也就是虚拟机/翻译器）设计基于以下设计约束：</p>
<ol type="1">
<li>协议无关：将包视为字节数组</li>
<li>通用（指令）</li>
<li>包数据引用最小</li>
<li>通过 C 语言的 <code>switch</code>
语句译码：为了保证译码效率，采用单地址格式编码</li>
<li>抽象机器的寄存器需要在物理寄存器中驻留</li>
</ol>
<p>这些约束导致采用<strong>累加器型</strong>机器是最为合适的。</p>
<h3 id="the-bpf-pseudo-machine">3.3 The BPF Pseudo-Machine</h3>
<h3 id="examples">3.4 Examples</h3>
<h3 id="parsing-packet-headers">3.5 Parsing Packet Headers</h3>
<p>这三节介绍了 BPF 的指令集设计，给出了一些例子，并解释了
<code>4 * ([k] &amp; 0xf)</code> 这一寻址方式的设计意图。</p>
<p>BPF
虚拟机的操作对象包括：一个累加器、一个寄存器、一个存储器、数据包和一个隐式的
PC。</p>
<p>BPF 的指令类型：</p>
<ul>
<li>访存指令在累加器/寄存器和存储器/数据包间移动数据</li>
<li>运算指令将累加器中的值和立即数进行运算</li>
<li>分支指令根据寄存器中的值是否满足条件改变 PC</li>
<li>返回指令返回过滤器的最终判断结果，为 TRUE 则接受数据包</li>
<li>若干杂项指令</li>
</ul>
<h3 id="filter-performance-measurements">3.6 Filter Performance
Measurements</h3>
<p>通过比较 BPF 和 CSPF 过滤器模型的执行指令数，可以发现 BPF
存在显著的性能优势。</p>
<p><img src="/img/BPF-CSPF-Fileter-Performance.png" srcset="/img/loading.gif" lazyload /></p>
<ul>
<li>Filter 1：BPF 快了 50%</li>
<li>Filter 2：BPF 快了 240%，这主要是由于 CSPF 一次只能处理 16
位的数据，处理一个 32 位数据需要两次运算</li>
<li>Filter 3：更大的性能差距，这是因为 CSPF 中有许多重复运算</li>
</ul>
<h2 id="applications">4 Applications</h2>
<p>BPF 的主要应用：tcpdump、arpwatch 等。</p>
<h2 id="conclusion">5 Conclusion</h2>
<p>BPF
是一个高效的、可伸缩的、可移植的网络监控模型，已经可以运行在大部分的 BSD
发行版上。</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/note/">note</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/paper/">paper</a>
                    
                      <a class="hover-with-bg" href="/tags/ebpf/">ebpf</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2024/03/06/%E6%96%87%E7%8C%AE%E9%98%85%E8%AF%BB-bpftime-userspace-eBPF-Runtime-for-Uprobe-Syscall-and-Kernel-User-Interactions/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">文献阅读: bpftime: userspace eBPF Runtime for Uprobe, Syscall and Kernel-User Interactions</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/11/05/%E6%96%87%E7%8C%AE%E9%98%85%E8%AF%BB%E4%B8%93%E9%A2%98-%E7%B3%BB%E7%BB%9F%E8%B0%83%E7%94%A8%E5%8A%A0%E9%80%9F/">
                        <span class="hidden-mobile">文献阅读专题:系统调用加速</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/valine@1/dist/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"y7tlaLEOoW5C1xBYm8VBo64Q-gzGzoHsz","appKey":"F7gylUefEEtQk24FEbvgfnBi","path":"window.location.pathname","placeholder":"此处留言","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          Fluid.plugins.initFancyBox('#valine .vcontent img:not(.vemoji)');
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> && <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>












  

  

  

  

  

  





<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>
